<template>
  <div class="dept-manage">
    <div class="query-form">
      <el-form :inline="true" :model="quForm" ref="queryForm">
        <el-form-item label="产品类别名称" prop="categoryName">
          <el-input v-model="quForm.categoryName" placeholder="请输入产品类别名称"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="quForm.status">
            <el-option v-for="item in statusList" :key="item.value" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset('queryForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="handleCreate">创建</el-button>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        <el-button type="info" @click="handleStatus(2)">禁用</el-button>
        <el-button type="success" @click="handleStatus(1)">启用</el-button>

      </div>
      <el-table :data="deptList" row-key="categoryId" border @selection-change="handleSelectionChange"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" default-expand-all>
        <el-table-column type="selection" width="55" />
        <el-table-column v-for="item in columns" :prop="item.prop" :label="item.label" :width="item.width"
          :key="item.prop" :formatter="item.formatter">
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 编辑弹窗 -->
    <el-dialog v-model="showEditDialog" title="编辑产品类别" width="500px" center>
      <el-form :model="editCategory" ref="editForm" :rules="rules">
        <el-form-item label="产品类别名称" prop="categoryName">
          <el-input v-model="editCategory.categoryName" />
        </el-form-item>
        <el-form-item label="产品类别描述" prop="remark">
          <el-input v-model="editCategory.remark"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 创建弹窗 -->
    <el-dialog v-model="showCreateDialog" title="创建产品类别" width="500px" center>
      <el-form :model="addCategory" ref="addForm" :rules="rules">
        <el-form-item label="产品类别名称" prop="categoryName">
          <el-input v-model="addCategory.categoryName" />
        </el-form-item>
        <el-form-item label="产品类别描述" prop="remark">
          <el-input v-model="addCategory.remark"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreateConfirm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除弹窗 -->
    <!-- <el-dialog v-model="showDeleteDialog" title="确定删除机构吗？" width="500px" center>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="primary" @click="handleDeleteConfirm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog> -->
  </div>
</template>
<script setup>
import api from '@/api'
import { nextTick, onMounted, reactive, ref, toRaw } from 'vue';
import { getCurrentInstance } from 'vue';

// 查询条件
const quForm = reactive({
  categoryName: '',
  status: 2
})
// 表格列
const columns = [
  {
    label: "编码",
    prop: "categoryId",
    width: 180,
  },
  {
    label: "产品类别名称",
    prop: "categoryName",

  },
  {
    label: "状态",
    prop: "status",
    width: 200,
    formatter: (row) => {
      if (row.status === 0) {
        return '启用'
      } else {
        return '禁用'
      }
    }
  },
  {
    label: "备注",
    prop: "remark",
    width: 200,
  },
]
// TODO
// 复用编辑和创建 1 --> 编辑 2 --> 创建
// const action = ref(1)
// 校验规则
const rules = {
  categoryName: [
    {
      required: true,
      message: '请输入产品类别名称',
      trigger: 'blur'
    }
  ]
}
// 当前实例
const { proxy } = getCurrentInstance()
// 部门列表
const deptList = ref([])
// 调用接口获取部门列表
onMounted(() => {
  getCategoryList()
})
// 编辑弹窗
const showEditDialog = ref(false)
// 创建弹窗
const showCreateDialog = ref(false)
// 删除弹窗
// const showDeleteDialog = ref(false)
// 部门状态
const statusList = [
  {
    label: '全部',
    value: 2,

  },
  {
    label: '启用',
    value: 0,
  },
  {
    label: '禁用',
    value: 1,
  },
]
// 删除类别列表ID
const deleteCategoryIds = ref([])
// 编辑类别
const editCategory = ref({
  categoryId: 1,
  categoryName: '',
  parentId: 0,
  remark: ''
})
// 创建类别
const addCategory = ref({
  categoryName: '',
  parentId: 0,
  remark: ''
})
// 批量删除
const handleBatchDelete = async () => {
  // console.log('...........');
  if (deleteCategoryIds.value.length > 0) {
    if (confirm('确定批量删除这些产品类别吗?')) {
      let res = await api.deleteCategory({ categoryIds: [...deleteCategoryIds.value] })
      if (res > 0) {
        proxy.$message.success('批量删除成功')
        deleteCategoryIds.value = []
        getCategoryList()
      }
    }
  }
}
// 获取多选列表
const handleSelectionChange = (vals) => {
  let arr = []
  vals.forEach(element => {
    arr.push(element.categoryId)
  });
  deleteCategoryIds.value = arr
}
// 获取部门列表
const getCategoryList = async () => {
  try {
    let data = await api.getCategoryTree()
    // console.log(data);
    deptList.value = data
  } catch (err) {
    console.log(err);
  }
}
// 查询产品类别
const handleQuery = async () => {
  try {

    let data
    if (quForm.status === 2 && !quForm.categoryName) {
      data = await api.getCategoryQuery()
    } else if (quForm.status === 2) {
      data = await api.getCategoryQuery({ categoryName: quForm.categoryName })
    } else {
      data = await api.getCategoryQuery({ ...quForm })
    }
    deptList.value = data
    handleReset('queryForm')
  } catch (err) {
    console.log(err);
  }
}
// 重置查询条件
const handleReset = (formName) => {
  proxy.$refs[formName].resetFields()
}
// 递归获取子级菜单id
const depth = (list, data) => {
  if (data.length === 0) return
  data.forEach(item => {
    list.push(item.categoryId)
    if (item.children) {
      depth(list, item.children)
    }
  })
}
// 删除类别
const handleDelete = async (row) => {
  try {
    // console.log('--------->delete');
    let childrenIds = []
    if (row) {
      deleteCategoryIds.value = [row.categoryId]
      if (row.children) {
        depth(childrenIds, row.children)
      }
    }

    if (confirm('确定删除产品类别吗？')) {
      let res = await api.deleteCategory({ categoryIds: [...deleteCategoryIds.value, ...childrenIds] })
      if (res > 0) {
        proxy.$message.success('删除成功')
        deleteCategoryIds.value = []
        getCategoryList()
      }

    }

  } catch (err) {
    console.log(err);
  }
}

// 编辑类别
const handleEdit = async (row) => {
  console.log(row);
  showEditDialog.value = true
  nextTick(() => {
    editCategory.value.categoryId = row.categoryId
    editCategory.value.remark = row.remark
    editCategory.value.parentId = row.parentId
    editCategory.value.categoryName = row.categoryName
  })
}
// 创建机构
const handleCreate = async () => {
  showCreateDialog.value = true
}
// 编辑确认
const handleEditConfirm = async () => {
  proxy.$refs.editForm.validate(async (valid) => {
    if (!valid) return
    try {
      let data = await api.updateCategory(editCategory.value)
      if (data > 0) {
        proxy.$message.success('修改成功')
        showEditDialog.value = false
        handleReset('editForm')
        getCategoryList()
      }
    } catch (err) {
      console.log(err);
    }
  })
}
// 创建确认
const handleCreateConfirm = async () => {
  proxy.$refs.addForm.validate(async (valid) => {
    if (!valid) {
      return
    }
    try {
      let res = await api.addCategory(addCategory.value)
      if (res) {
        proxy.$message.success('创建成功')
        handleReset('addForm')
        showCreateDialog.value = false
        getCategoryList()
      }
    } catch (err) {
      console.log(err);
    }
  })

}
// 启用禁用
const handleStatus = async (status) => {
  try {
    if (deleteCategoryIds.value.length === 0) return
    if (status === 1) {

      if (confirm('确定启用吗?')) {
        // console.log(deleteDeptIds.value);
        let res = await api.changeStatusCategory({ categoryIds: deleteCategoryIds.value, status: 0 })
        if (res > 0) {
          proxy.$message.success('启用成功')
          getCategoryList()
        }
      }
    } else {
      if (confirm('确定禁用吗?')) {
        let res = await api.changeStatusCategory({ categoryIds: deleteCategoryIds.value, status: 1 })
        if (res > 0) {
          proxy.$message.success('禁用成功')
          getCategoryList()
        }
      }
    }

  } catch (err) {
    console.log(err);
  }
}
</script>
<style lang="scss" scoped>
.dept-manage {
  height: 100%;
  overflow-y: scroll;
}

.query-form {
  display: flex;
  align-items: center;
  background: #fff;
  padding-top: 18px;
  margin-bottom: 16px;
  padding-left: 20px;
  border-radius: 4px;
}

.base-table {
  background: #fff;
  border-radius: 4px;

  .action {
    padding: 15px;
    border-bottom: 1px solid #eee;
  }
}
</style>
